import {
  _decorator,
  AudioClip,
  AudioSource,
  BoxCollider2D,
  Collider2D,
  Component,
  Contact2DType,
  ERigidBody2DType,
  find,
  game,
  instantiate,
  Label,
  Node,
  Prefab,
  resources,
  RigidBody2D,
} from "cc";
const { ccclass, property } = _decorator;

@ccclass("myGame")
export class myGame extends Component {
  score = 0;
  blockNums = 0;
  isWin = false;

  @property(AudioClip)
  public audioZhiyin: AudioClip = null!;

  @property(AudioClip)
  public audioAiyou: AudioClip = null;

  start() {
    const bttomWall = find("Canvas/background/wall_bottom").getComponent(
      BoxCollider2D
    );

    this.generateBlocks();
    this.refreshScore();

    game.on("add-score", this.addScore, this);
    game.on("play-zhiyin", this.playZhiyin, this);
    bttomWall.on(Contact2DType.BEGIN_CONTACT, this.onBottomWallContact, this);
  }

  update(deltaTime: number) {}

  gameInit() {
    this.score = 0;
    this.isWin = false;

    this.resetBall();
    this.clearBlock();
    this.generateBlocks();
    this.refreshScore();
  }

  resetBall() {
    const ball = find("Canvas/ball");
    const body = ball.getComponent(RigidBody2D);
    body.type = ERigidBody2DType.Static;
    ball.setPosition(0, -200);
  }

  playZhiyin() {
    const aduioSource = this.node.getComponent(AudioSource);
    aduioSource.playOneShot(this.audioZhiyin);
  }

  playAiyou() {
    const aduioSource = this.node.getComponent(AudioSource);
    aduioSource.playOneShot(this.audioAiyou);
  }

  gameEnd() {
    this.isWin = true;
    this.playAiyou();
  }

  onBottomWallContact(selfCollider: Collider2D, otherCollider: Collider2D) {
    if (this.isWin) {
      return;
    }
    if (otherCollider.node.name === "ball") {
      // 游戏失败
      const loseNode = find("Canvas/ui/lose");
      loseNode.active = true;
      this.gameEnd();
    }
  }

  refreshScore() {
    const label = find("Canvas/ui/score").getComponent(Label);

    label.string = `分数：${this.score}`;
  }

  addScore() {
    this.score += 1;
    this.refreshScore();
    this.checkWin();
  }

  clearBlock() {
    const layer = find("Canvas/blocks");
    layer.removeAllChildren();
  }

  generateBlocks() {
    const layer = find("Canvas/blocks");

    resources.load("block", Prefab, (err, prefab) => {
      for (let i = 0; i < 8; i++) {
        for (let j = 0; j < 2; j++) {
          const newBlock = instantiate(prefab);
          layer.addChild(newBlock);
          newBlock.setPosition(-210 + i * 60, 80 + j * 30);

          this.blockNums = layer.children.length;
        }
      }
    });
  }

  checkWin() {
    if (this.score === this.blockNums) {
      // 游戏胜利
      const winNode = find("Canvas/ui/win");
      winNode.active = true;
      this.gameEnd();
    }
  }

  handleReplay() {
    const winNode = find("Canvas/ui/win");
    const loseNode = find("Canvas/ui/lose");

    winNode.active = false;
    loseNode.active = false;

    this.gameInit();
  }
}
